package com.microservice.salmon.service.goods.specifications;

import com.microservice.salmon.db.entities.SpecificationsGroup;
import com.microservice.salmon.db.entities.SpecificationsItem;
import com.microservice.salmon.db.mapper.SpecificationsGroupMapper;
import com.microservice.salmon.db.mapper.SpecificationsItemMapper;
import com.microservice.salmon.service.exception.ResourceException;
import com.salmon.common.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class SpecificationsServiceImpl implements SpecificationsService {

    @Autowired
    private SpecificationsGroupMapper specificationsGroupMapper;

    @Autowired
    private SpecificationsItemMapper specificationsItemMapper;

    public List<SpecificationsGroup> queryGroupByCategoryId(Integer categoryId) {
        SpecificationsGroup specificationsGroup = new SpecificationsGroup();
        specificationsGroup.setGoodsCatId(categoryId);
        specificationsGroup.setDataFlag(Boolean.TRUE);
        List<SpecificationsGroup> list = specificationsGroupMapper.select(specificationsGroup);
        if(CollectionUtils.isEmpty(list))
            throw new ResourceException(ApiResponse.Status.NOT_FOUND_SPEC_GROUP);
        return list;
    }

    /**
     * 获取规格项（规格参数)
     *
     * @param groupId 规格组的ID
     * @return
     */
    @Override
    public List<SpecificationsItem> querySpecItemBySpecGroup(Integer groupId) {
        SpecificationsItem item = new SpecificationsItem();
        item.setSpecGroupId(groupId);
        item.setDataFlag(Boolean.TRUE);
        List<SpecificationsItem> list = specificationsItemMapper.select(item);
        if(CollectionUtils.isEmpty(list))
            throw new ResourceException(ApiResponse.Status.NOT_FOUND_SPEC_ITEM);
        return list;
    }

    @Override
    public int deleteSpecParam(Integer id) {
        int count = specificationsItemMapper.deleteByPrimaryKey(id);
        if(count != 1) {
            throw new ResourceException(ApiResponse.Status.DELETE_ERROR);
        }
        return count;
    }

    @Override
    public int modifySpecParam(SpecificationsItem specificationsItem) {
        if(specificationsItem.getId() == null)
            throw new ResourceException(ApiResponse.Status.NO_PRIMARY_KEY);
        int count = specificationsItemMapper.updateByPrimaryKeySelective(specificationsItem);
        if(count != 1) {
            throw new ResourceException(ApiResponse.Status.DELETE_ERROR);
        }
        return count;
    }

    @Override
    public int add(SpecificationsItem specificationsItem) {
        specificationsItem.setId(null);
        int count = specificationsItemMapper.insertSelective(specificationsItem);
        if(count != 1) {
            throw new ResourceException(ApiResponse.Status.DELETE_ERROR);
        }
        return count;
    }
}
